<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <meta http-equiv="pragma" content="no-cache"/>
    <meta http-equiv="cache-control" content="no-cache"/>
    <meta http-equiv="expires" content="0"/>
    <!-- 管局要求保持备案名称和网站使用名称一致 -->
    <title>登录页</title>
    <link rel="stylesheet" type="text/css" th:href="@{/y9static/y9new/css/default.css}"/>
    <link rel="stylesheet" type="text/css" th:href="@{/y9static/css/y9-xxx/styles.css}"/>
    <link rel="stylesheet" type="text/css" th:href="@{/y9static/y9new/css/demo.css}"/>
    <link rel="stylesheet" type="text/css" th:href="@{/y9static/y9new/css/loaders.css}"/>
    <link rel="stylesheet" type="text/css" th:href="@{/y9static/y9new/css/layerMsg.css}"/>
    <link rel="stylesheet" type="text/css" th:href="@{/y9static/y9new/css/verify.css}"/>
    <script type="text/javascript" th:src="@{/y9static/js/base64.js}"></script>
    <script type="text/javascript" th:src="@{/y9static/y9new/js/jquery-2.1.1.min.js}"></script>
    <script type="text/javascript" th:src="@{/y9static/js/jquery/jquery.cookie.js}"></script>
    <script type="text/javascript" th:src="@{/y9static/y9new/js/jsencrypt.min.js}"></script>
    <style type="text/css">
        body{

        }
    </style>
</head>

<body>
<div class="logo">
<!--    <img th:src="@{/y9static/y9new/img/cloud.png}">-->
    <span class="left">
        <!--xxx系统-->
    </span>
    <span class="right" id="currentTimer">
    </span>
</div>
<div class="login" id="tunnel">
    <div class="login_title">
        <span onclick="changeLoginType(0)">用户登录</span>
    </div>

    <div class="login_fields">
        <form method="post" id="fm1" th:object="${credential}">
            <div class="alert alert-danger" th:if="${#fields.hasErrors('*')}">
                登录失败：<span th:each="err : ${#fields.errors('*')}" th:utext="${err}"/>
            </div>
            <div class="login_fields__user">
                <div class="icon"><img alt="" th:src="@{/y9static/y9new/img/user_icon_copy.png}"/></div>
                <input id="username" placeholder="用户名" type="text" autocomplete="off" value="" oninput="inputEvent()" onblur="getTenant();"/>
                <input id="username1" name="username" style="width: 150px;" tabindex="1" autocomplete="false" htmlescape="true" type="hidden"/>
                <input id="tenantShortName" name="tenantShortName" style="width: 150px;" autocomplete="false" htmlescape="true" type="hidden"/>
                <div class="validation"><img alt="" th:src="@{/y9static/y9new/img/tick.png}"/></div>
            </div>
            <div class="login_fields__password">
                <div class="icon"><img alt="" th:src="@{/y9static/y9new/img/lock_icon_copy.png}"/></div>
                <input id="password" tabindex="2" type="text" htmlescape="true" autocomplete="off" placeholder="请输入您的密码" onfocus="this.type='password'"/>
                <input id="password1" name="password" htmlescape="true" autocomplete="off" type="hidden"/>

                <div class="validation"><img alt="" th:src="@{/y9static/y9new/img/tick.png}"/></div>
            </div>
            <!-- 表单隐藏数据块开始 -->
            <input type="hidden" id="loginType" name="loginType" value="loginName"/>
            <input type="hidden" id="captchaKey" name="captchaKey" value=""/>
            <input type="hidden" id="noLoginScreen" name="noLoginScreen" value="false"/>
            <input type="hidden" id="screenDimension" name="screenDimension" value=""/>
            <input type="hidden" id="pwdEcodeType" name="pwdEcodeType" value=""/>
            <input type="hidden" name="execution" th:value="${flowExecutionKey}"/>
            <input type="hidden" name="_eventId" value="submit"/> <input type="hidden" name="geolocation"/>
            <!-- 表单隐藏数据块结束 -->
        </form>
        <!--点选验证码  -->
        <div id="mpanel6"></div>
        <div class="login_fields__submit">
            <input type="button" value="登录"/>
        </div>
    </div>
    <div></div>
    <div class="linkOtherSystem">
        <a href="https://www.youshengyun.com/risecloud">云体验</a>
        <a href="https://dev.youshengyun.com/admin-dev/">云开发</a>
        <a href="https://www.youshengyun.com/y9home/">云租户</a>
        <a href="https://www.youshengyun.com/admin-ops/">云后台</a>
        <a href="https://www.risesoft.net">有生软件</a>
        <a href="https://www.zgcsa.net/" target="_blank">中关村软联</a>
    </div>
    <div class="success"></div>
    <div class="toolTips" style="display: none">
        <ul id="toolTipsUl"></ul>
    </div>
</div>
<div class="footer">
    <!--<div>
        <span>北京有生博大软件股份有限公司 版权所有</span>
        <a href="https://beian.miit.gov.cn/" target="_blank">京ICP备16060306号-4</a>
        <a href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=11010802026965" target="_blank"><img th:src="@{/y9static/y9new/img/police.png}"/>京公网安备11010802026965号</a>
    </div>-->
    <span>建议您使用1920x1080分辨率，IE9.0或以上版本浏览器访问本站，以获得最佳用户体验。 技术支持：0755-821072292</span>
</div>

<link rel="stylesheet" type="text/css" th:href="@{/y9static/y9new/layui/css/layui.css}"/>
<script type="text/javascript" th:src="@{/y9static/y9new/js/verify.js}"></script>
<script type="text/javascript" th:src="@{/y9static/y9new/layui/layui.js}"></script>
<script type="text/javascript" th:src="@{/y9static/y9new/js/layerMsg.js}" charset="utf-8"></script>
<script type="text/javascript">
    var ctx = "[(${#request.getContextPath()})]";
    var canGetCookie = 1; //是否支持存储Cookie 0 不支持 1 支持
    var ajaxmockjax = 1; //是否启用虚拟Ajax的请求响 0 不启用  1 启用
    var inputTimer = null;
    $(function () {
        changeLoginType($.cookie("loginTip"));
        validateIE();
    });

    function validateIE() {
        try {
            $("#screenDimension").val(window.screen.width + '*' + window.screen.height);
        } catch (e) {
        }
    }

    function inputEvent() {
        if (inputTimer) {
            clearTimeout(inputTimer);
        }
        let params = {loginName: $("#username").val()};
        if (!$("#username").val()) {
            $(".toolTips").attr({style: "display: none;"});
            return null;
        }
        inputTimer = setTimeout(() => {
            fetch(ctx + "/api/loginNameAndTenants", {
                method: "POST",
                credentials: "include",
                headers: {
                    "Content-Type":
                        "application/x-www-form-urlencoded;charset=UTF-8",
                },
                body: Object.keys(params).map((key) => {
                    return (encodeURIComponent(key) + "=" + encodeURIComponent(params[key]));
                }).join("&"),
            }).then((response) => {
                return response.json();
            }).then((data) => {
                $("#toolTipsUl").empty();
                $(".toolTips").attr({style: "display: flex;"});
                data.length && data.map((item) => {
                    $("<li></li>", {text: item.loginName, id: item.tenantShortName}).appendTo("#toolTipsUl").on("click", mouseClickEvent);
                });
            });
        }, 250);
    }

    function getTenant() {
        var userName = $('#username').val();
        if ($.trim(userName).length > 0 && userName.indexOf("@") != -1) {
            var tenantName = userName.split("@");
            userName = tenantName[0].split("&");
            $("#username1").val(tenantName[0]);
            $.ajax({
                type: 'POST',
                dataType: 'json',
                data: {
                    loginName: userName[0],
                    tenantName: tenantName[1]
                },
                url: ctx + '/api/getTenants',
                success: function (res) {
                    if (res.length <= 0) {
                        layer.msg("当前用户不存在或者已禁用!");
                        return;
                    }
                    $('#tenantShortName').val(res[0].tenantShortName);
                }
            });
        }
    }

    function mouseClickEvent() {
        $('#tenantShortName').val(this.id);
        var userName = this.innerText;
        $('#username').val(userName);
        if ($.trim(userName).length > 0 && userName.indexOf("@") != -1) {
            $('#username1').val(userName.split("@")[0]);
        }
        $("#toolTipsUl").empty();
        $(".toolTips").attr({style: "display: none;"});
        $('#password').focus();
    }

    $(document).keydown(function (e) {
        // 上下选择事件
        function shooseItem(value) {
            let activeIndex = null, lisLength = $("#toolTipsUl").children().length;
            lisLength &&
            $("#toolTipsUl li").each(function (index, element) {
                if (this.className.includes("active")) {
                    this.className = "";
                    activeIndex = index;
                    return true;
                }
            });

            if (!lisLength && activeIndex === null) {
                return false;
            }
            if (value === 38 && activeIndex) {
                $("#toolTipsUl").children().eq(activeIndex - 1).addClass("active");
                return true;
            }
            if (value === 38 && !activeIndex) {
                $("#toolTipsUl").children().eq(lisLength - 1).addClass("active");
                return true;
            }
            if (value === 40 && (activeIndex === null || activeIndex + 1 === lisLength)) {
                $("#toolTipsUl").children().eq(0).addClass("active");
                return true;
            }
            if (value === 40 && activeIndex + 1 <= lisLength) {
                $("#toolTipsUl").children().eq(activeIndex + 1).addClass("active");
                return true;
            }
        }

        // 回车键事件
        if (e.which === 13) {
            enterEvent();
        }
        // 上下按键
        if (e.which === 38 || e.which === 40) {
            e.which === 38 && shooseItem(38);
            e.which === 40 && shooseItem(40);
        }
    });

    function enterEvent() {
        let shoseEvent = false;
        $("#toolTipsUl").children().length && $("#toolTipsUl li").each(function (index, element) {
            if (this.className.includes("active")) {
                shoseEvent = true;
                $('#tenantShortName').val(this.id);
                var userName = this.innerText;
                $('#username').val(userName);
                if ($.trim(userName).length > 0 && userName.indexOf("@") != -1) {
                    $('#username1').val(userName.split("@")[0]);
                }
                $("#toolTipsUl").empty();
                $(".toolTips").attr({style: "display: none;"});
                $('#password').focus();
                return true;
            }
        });
        if (!shoseEvent) {
            $('input[type="button"]').click();
        }
    }

    var open = 0;
    layui.use("layer", function () {
        var option = {
            type: "success",
            position: "top-center",
            showicon: true,
            time: 3000,
            title: "登录提示",
            content: "提示",
            shadow: false,
            shadowclickclose: true,
            autoclose: true,
            callback: function (data, obj) {
                obj.ele.close(0);
            },
        };
        //非空验证
        $('input[type="button"]').click(function () {
            var username = $('#username').val();
            var username1 = $('#username1').val();
            var password = $('#password').val();
            var tenantShortName = $("#tenantShortName").val();
            if (username == "") {
                option.type = "warn";
                option.content = "请输入您的账号";
                WfMsg(option);
            } else if (password == "") {
                option.type = "warn";
                option.content = "请输入密码";
                WfMsg(option);
            } else {
                $.when(
                    $.ajax({
                        async: false,
                        cache: false,
                        type: "GET",
                        url: ctx + '/api/getRandom',
                        dataType: "json",
                        success: function (y9Result) {
                            if (y9Result.success) {
                                $('#pwdEcodeType').val(y9Result.data);
                            }
                        }
                    })
                ).done(function () {
                    $.ajax({
                        async: false,
                        cache: false,
                        type: "POST",
                        url: ctx + '/api/checkSsoLoginInfo',
                        data: {
                            username: encode64(username1),
                            password: encrypt($('#pwdEcodeType').val(), encode64(password)),
                            tenantShortName: tenantShortName,
                            pwdEcodeType: $('#pwdEcodeType').val()
                        },
                        dataType: "json",
                        success: function (data) {
                            if (data.success) {
                                $("#mpanel6").attr({style: "display: block;"});
                            } else {
                                var msg = data.msg;
                                if (msg != null && msg.length > 0) {
                                    option.type = "warn";
                                    option.content = msg;
                                    WfMsg(option);
                                }
                            }
                        }
                    })
                }).fail(function () {
                    option.type = "warn";
                    option.content = "获取随机数失败。";
                    WfMsg(option);
                });
            }
        });
    });
    //全屏
    var fullscreen = function () {
        elem = document.body;
        if (elem.webkitRequestFullScreen) {
            elem.webkitRequestFullScreen();
        } else if (elem.mozRequestFullScreen) {
            elem.mozRequestFullScreen();
        } else if (elem.requestFullScreen) {
            elem.requestFullscreen();
        } else {
            //浏览器不支持全屏API或已被禁用
        }
    };
</script>
<script id="vs" type="x-shader/x-vertex">
    varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }
</script>
<script id="fs" type="x-shader/x-fragment">
    uniform sampler2D map; uniform vec3 fogColor; uniform float fogNear; uniform float fogFar; varying vec2 vUv; void main() { float depth = gl_FragCoord.z / gl_FragCoord.w; float fogFactor = smoothstep( fogNear, fogFar, depth ); gl_FragColor = texture2D( map, vUv ); gl_FragColor.w *= pow( gl_FragCoord.z, 20.0 ); gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor ); }
</script>


<script type="text/javascript">
    <!--    右上角显示的时间      -->
    function getCurrentTime() {
        const now = new Date();
        const year = now.getFullYear();
        const month = (now.getMonth() + 1).toString().padStart(2, '0');
        const day = now.getDate().toString().padStart(2, '0');
        const hours = now.getHours().toString().padStart(2, '0');
        const minutes = now.getMinutes().toString().padStart(2, '0');
        const seconds = now.getSeconds().toString().padStart(2, '0');

        return `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`;
    }
    document.getElementById("currentTimer").innerText = getCurrentTime();
    var currentTimer = null;
    if (currentTimer){
        clearInterval(currentTimer);
    }
    currentTimer = setInterval(function () {
        document.getElementById("currentTimer").innerText = getCurrentTime();
    }, 1000)


    let changeLoginModuleTimer = null;

    function changeLoginModule(value) {
        $("body .toolTips").attr({style: "display: none;"});
        if (changeLoginModuleTimer) {
            clearTimeout(changeLoginModuleTimer);
        }

        if (0 == value) {
            document.getElementById("tunnel").animate(
                [{transform: "rotateY(0)"}, {transform: "rotateY(360deg)"}],
                {
                    duration: 850,
                    timingFunction: "ease",
                }
            );
            document.getElementsByClassName("login_fields")[0].style.display = "none";
        } else {
            document.getElementById("tunnel").animate(
                [{transform: "rotateY(360deg)"}, {transform: "rotateY(0)"}],
                {
                    duration: 850,
                    timingFunction: "ease",
                }
            );
        }
        changeLoginModuleTimer = setTimeout(() => {
            $.cookie("loginModuleTip", value, {
                expires: 365
            });
            if (0 == value) {
                layui.use('layer', function () {
                    var layer = layui.layer;
                    layer.closeAll();
                });
                $("body .login_title").children().eq(0).html("关联系统登录");
                $("body .login_title").children().eq(0).removeAttr("onclick");
                $("body .login_title").attr({style: "justify-content: center;"});
                $("body .login_title").children().eq(1).attr({style: "display: none;"});
                $("body .login_title").children().eq(2).attr({style: "display: none;"});
                $(".disclaimer").children().eq(0).attr({style: "display: none;margin-bottom: 5px;"});
                $(".disclaimer").children().eq(1).attr({style: "display: '';margin-bottom: 5px;"});
                $(".linkOtherSystem").attr({style: "display: flex;"});
                $("body .qvcode").attr({style: "display: none;"});
            } else {
                changeLoginType($.cookie("loginTip"));
                $("body .login_title").children().eq(0).html("用户登录");
                $("body .login_title").children().eq(0).attr("onclick", "changeLoginType(0);");
                $("body .login_title").attr({style: "justify-content: space-between;"});
                $("body .login_title").children().eq(0).attr({style: "color: #ffffff;"});
                $("body .login_title").children().eq(1).attr({style: "display: '';"});
                $("body .login_title").children().eq(2).attr({style: "display: '';"});
                $(".disclaimer").children().eq(0).attr({style: "display: '';margin-bottom: 5px;"});
                $(".disclaimer").children().eq(1).attr({style: "display: none;margin-bottom: 5px;"});
                //document.getElementsByClassName("login_fields")[0].style.display ="";
                document.getElementsByClassName("linkOtherSystem")[0].style.display = "none";
            }
        }, 530);
    }

    function changeLoginType(value) {
        if (1 == value) {
            //扫码登录
            $("body .login_fields").attr({style: "display: none;"});
            $("body .qvcode").fadeIn();
            $("body .login_title").children().eq(0).attr({style: "color: #DFDFDF"});
            $("body .login_title").children().eq(2).attr({style: "color: #ffffff"});
            getQRCode();
        } else {
            //用户名密码登录
            layui.use('layer', function () {
                var layer = layui.layer;
                layer.closeAll();
            });
            $("body .qvcode").attr({style: "display: none;"});
            $("body .login_fields").fadeIn();
            $("body .login_title").children().eq(2).attr({style: "color: #DFDFDF"});
            $("body .login_title").children().eq(0).attr({style: "color: #ffffff"});
        }
        $.cookie("loginTip", value, {
            expires: 365
        });
    }

    //获取二维码
    var uuid = "";

    function getQRCode() {
        layui.use('layer', function () {
            var layer = layui.layer;
            layer.closeAll();
        });
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ctx + '/api/getQRCode',
            success: function (res) {
                if (res.success && '' != res.img) {
                    uuid = res.uuid;
                    var imgSrc = res.img;
                    var imgg = "<img src=" + imgSrc + " />";
                    $("#img_container").empty().append(imgg);
                    keepPool();
                } else {
                    layer.msg("获取二维码失败，请稍后重试。");
                }
            }
        });
    }

    //轮询二维码是否被扫描被扫描并获取用户ID
    function keepPool() {
        $.ajax({
            type: 'POST',
            dataType: 'json',
            data: {uuid: uuid},
            url: ctx + '/api/getScanResult',
            success: function (res) {
                var scanResult = res.scanResult;
                if (scanResult == '1' || scanResult == 1) {
                    layer.msg("扫描成功，正在登录。");
                    var userId = res.userId;
                    $('#tenantShortName').val(encode64(userId));
                    $("#username1").val(encode64(userId));
                    $("#password1").val(encode64(userId));
                    $("#loginType").val('qrCode');
                    $("#fm1").submit();
                } else if (scanResult == '0' || scanResult == 0) {
                    if ($.cookie("loginTip") == 1 && $.cookie("loginModuleTip") != 0) {
                        layer.msg("该二维码已经失效，请点击该二维码重新获取。", {time: '-1'});
                    }
                } else {
                    setTimeout("keepPool()", 1000);
                }
            }
        });
    }
</script>
</body>
</html>